package com.example.audiostreaming.activity;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.audiostreaming.R;
import com.example.audiostreaming.adapters.AdapterTrackRv;
import com.example.audiostreaming.base.BaseActivity;
import com.example.audiostreaming.implement.ImplDetailLogic;
import com.example.audiostreaming.implement.ImplPlayerLogic;
import com.example.audiostreaming.implement.SubscriptionPresenter;
import com.example.audiostreaming.interfaces.IDetailViewCallback;
import com.example.audiostreaming.interfaces.IPlayerViewCallback;
import com.example.audiostreaming.interfaces.ISubscriptionPresenterCallback;
import com.example.audiostreaming.utils.UtilConstants;
import com.example.audiostreaming.utils.UtilLog;
import com.example.audiostreaming.utils.UtilUI;
import com.example.audiostreaming.views.ViewRoundRectImageView;
import com.example.audiostreaming.views.ViewUILoader;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.ms.square.android.expandabletextview.ExpandableTextView;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import java.util.List;

import static com.example.audiostreaming.base.BaseApplication.getAppContext;
import static com.example.audiostreaming.base.BaseApplication.getHandler;
import static com.ximalaya.ting.android.opensdk.util.Utils.getContext;

/**
 * 详情界面
 */
public class DetailActivity extends BaseActivity {

    private static final String TAG = "DetailActivity";

    private ViewRoundRectImageView mDetailAlbumSmallCoverIv;
    private TextView mDetailAlbumTitleTv;
    private TextView mDetailAlbumAuthorTv;
    private ImplDetailLogic mInstanceImplDetailLogic;
    private DetailViewCallback mDetailViewCallback;
    private TextView mDetailAlbumSubCountTv;
    private ExpandableTextView mDetailAlbumIntroTv;
    private int mCurrentPage = 1;//当前页面
    private long mCurrentId = -1;//当前ID
    private RecyclerView mDetailAlbumListRv;
    private AdapterTrackRv mAdapterDetailAlbumRv;
    private ViewUILoader mUiLoader;
    private FrameLayout mContainer;
    private View mDetailPlayControlContainer;
    private ImageView mDetailPlayControlIv;
    private TextView mDetailPlayControlTv;
    private ImplPlayerLogic mInstanceImplPlayerLogic;
    private PlayerViewCallBack mPlayerViewCallBack;
    private final static int DEFAULT_PLAY_INDEX = 0;
    private TwinklingRefreshLayout mTwinklingRefreshLayout;
    private boolean mIsLoadMore = false;
    private String mCurrentTrackTitle;
    private TextView mSubBtn;
    private SubscriptionPresenter mSubscriptionPresenter;
    private SubscriptionPresenterCallback mSubscriptionPresenterCallback;
    private Album mCurrentAlbum;


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        initView();
        initPresenter();

        updateSubSate();
        updatePlaySate(mInstanceImplPlayerLogic.isPlaying());

        initEvent();
    }



    private void initPresenter() {
        mInstanceImplDetailLogic = ImplDetailLogic.getInstanceImplDetailLogic();//获取详情界面逻辑实现层的单例对象
        mDetailViewCallback = new DetailViewCallback();
        mInstanceImplDetailLogic.registerViewCallback(mDetailViewCallback); //设置注册通知UI界面更新的回调

        mInstanceImplPlayerLogic = ImplPlayerLogic.getInstanceImplPlayerLogic();
        mPlayerViewCallBack = new PlayerViewCallBack();
        mInstanceImplPlayerLogic.registerViewCallback(mPlayerViewCallBack);

        mSubscriptionPresenter = SubscriptionPresenter.getInstance();
        mSubscriptionPresenter.getSubscriptionList();
        mSubscriptionPresenterCallback = new SubscriptionPresenterCallback();
        mSubscriptionPresenter.registerViewCallback(mSubscriptionPresenterCallback);
    }

    private void initView() {
        initNavBar(true,"详情");
        mContainer = findViewById(R.id.container);//容器
        if (mUiLoader==null) {

            mUiLoader = new ViewUILoader(this) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    return createSussessView(container);
                }
            };
            mContainer.removeAllViews();
            mContainer.addView(mUiLoader);
            mUiLoader.setOnRetryClickListener(new OnRetryClickListener());
        }


        mDetailAlbumSmallCoverIv = findViewById(R.id.detailAlbum_small_cover_iv);
        mDetailAlbumTitleTv = findViewById(R.id.detailAlbum_title_tv);
        mDetailAlbumAuthorTv = findViewById(R.id.detailAlbum_author_tv);
        mDetailAlbumSubCountTv = findViewById(R.id.sub_count_tv);
        mDetailAlbumIntroTv = findViewById(R.id.detailAlbum_intro_tv);

        mDetailPlayControlContainer = findViewById(R.id.detail_play_control_container);
        mDetailPlayControlIv = findViewById(R.id.detail_play_control_iv);
        mDetailPlayControlTv = findViewById(R.id.detail_play_control_tv);
        mDetailPlayControlTv.setSelected(true);

        mSubBtn = findViewById(R.id.detail_sub_btn);
    }

    private void initEvent() {
            mDetailPlayControlContainer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mInstanceImplPlayerLogic != null) {

                        //判断播放器是否有播放列表
                        boolean hasPlayList = mInstanceImplPlayerLogic.hasPlayList();
                        if (hasPlayList) {
                            //控制播放器状态
                            handlePlayControl();
                        }else {
                            handleNoPlayList();
                        }

                    }
                }
            });
        mSubBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSubscriptionPresenter != null) {
                    boolean isSub = mSubscriptionPresenter.isSub(mCurrentAlbum);
                    //如果已订阅，那么就取消订阅。如果没有订阅，那么就去订阅
                    if (isSub) {
                        mSubscriptionPresenter.deleteSubscription(mCurrentAlbum);
                    }else {
                        mSubscriptionPresenter.addSubscription(mCurrentAlbum,true);
                    }
                    UtilLog.d(TAG,"点击订阅状态 ==> "+isSub);
                }

            }
        });
    }

    private View createSussessView(ViewGroup container) {
        View detailListView = LayoutInflater.from(getContext()).inflate(R.layout.activity_detail_list, container, false);


        //RecyclerView
        mDetailAlbumListRv = detailListView.findViewById(R.id.detailAlbum_List_Rv);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getAppContext());
        mDetailAlbumListRv.setLayoutManager(linearLayoutManager);
        mAdapterDetailAlbumRv = new AdapterTrackRv();
        mDetailAlbumListRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = UtilUI.dip2px(view.getContext(), 0);//dp转成px像素
                outRect.bottom = UtilUI.dip2px(view.getContext(), 3);
                outRect.left = UtilUI.dip2px(view.getContext(), 3);
                outRect.right = UtilUI.dip2px(view.getContext(), 3);
            }
        });
        mDetailAlbumListRv.setAdapter(mAdapterDetailAlbumRv);
        mAdapterDetailAlbumRv.setOnDetailAlbumItemClickListener(new OnDetailAlbumItemClickListener() );


        //TwinklingRefreshLayout 闪烁刷新布局
        mTwinklingRefreshLayout = detailListView.findViewById(R.id.refresh_layout);
        mTwinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mTwinklingRefreshLayout.finishRefreshing();
                        Toast.makeText(DetailActivity.this,"刷新内容完成",Toast.LENGTH_SHORT).show();
                    }
                },1000);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                //去加载更多内容
                if (mInstanceImplDetailLogic != null) {
                    mInstanceImplDetailLogic.pullUpLoadMoreDetailAlbumListData();
                    mIsLoadMore = true;
                }
            }
        });



        return detailListView;
    }

    /**
     * 设置订阅按钮的状态
     */
    private void updateSubSate() {
        if (mSubscriptionPresenter != null) {
            boolean isSub = mSubscriptionPresenter.isSub(mCurrentAlbum);
            mSubBtn.setText(isSub?R.string.cancel_sub_text:R.string.sub_text);
            UtilLog.d(TAG,"初始订阅状态 ==> "+isSub);
        }
    }

    /**
     * 根据播放状态修改图标和文字
     * @param playing
     */
    private void updatePlaySate(boolean playing) {
        if (mDetailPlayControlIv != null&&mDetailPlayControlTv!=null) {
            mDetailPlayControlIv.setImageResource(playing? R.drawable.selector_detail_play_control_stop : R.drawable.selector_detail_play_control_play);
            if (!playing) {
                mDetailPlayControlTv.setText("点击播放");
            }else {
                if (!TextUtils.isEmpty(mCurrentTrackTitle)) {
                    mDetailPlayControlTv.setText(mCurrentTrackTitle);
                }
            }
        }
    }

    private void handlePlayControl() {
        if (mInstanceImplPlayerLogic.isPlaying()) {
            //正在播放，那么就暂停
            mInstanceImplPlayerLogic.pause();
        }else {
            mInstanceImplPlayerLogic.play();
        }
    }

    /**
     * 处理播放器没有播放内容的情况
     */
    private void handleNoPlayList() {
        if (mDetailViewCallback != null) {
            List<Track> currentDetailAlbumTracks = mDetailViewCallback.getCurrentDetailAlbumTracks();
            if (mInstanceImplPlayerLogic != null) {
                mInstanceImplPlayerLogic.setPlayListData(currentDetailAlbumTracks,DEFAULT_PLAY_INDEX);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mInstanceImplDetailLogic != null) {
            mInstanceImplDetailLogic.unRegisterViewCallback(mDetailViewCallback);
            mInstanceImplDetailLogic = null;
        }
        if (mInstanceImplPlayerLogic != null) {
            mInstanceImplPlayerLogic.unRegisterViewCallback(mPlayerViewCallBack);
            mInstanceImplPlayerLogic = null;
        }
        if (mSubscriptionPresenter != null) {
            mSubscriptionPresenter.unRegisterViewCallback(mSubscriptionPresenterCallback);
            mSubscriptionPresenter = null;
        }
    }




    /**
     * 详情专辑界面UI视图回调的内部类
     */
    private class DetailViewCallback implements IDetailViewCallback{

        private List<Track> mCurrentDetailAlbumTracks=null;
        public List<Track> getCurrentDetailAlbumTracks(){
            return mCurrentDetailAlbumTracks;
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
        @Override
        public void onSetDetailAlbumUI(Album album) {
            mCurrentAlbum = album;
            mCurrentId = album.getId();
            //获取详情专辑的曲目列表内容
            if (mInstanceImplDetailLogic != null) {
                mInstanceImplDetailLogic.getDetailAlbumListData((int) mCurrentId,mCurrentPage);
            }

            if (mDetailAlbumTitleTv != null) {
                mDetailAlbumTitleTv.setText(album.getAlbumTitle());
            }
            if (mDetailAlbumAuthorTv != null) {
                mDetailAlbumAuthorTv.setText(album.getAnnouncer().getNickname());
            }
            if (mDetailAlbumSmallCoverIv != null) {
                String coverUrlLarge = album.getCoverUrlLarge();
                if (!TextUtils.isEmpty(coverUrlLarge)) {
                    Picasso.with(getAppContext()).load(coverUrlLarge).into(mDetailAlbumSmallCoverIv);
                }else {
                    mDetailAlbumSmallCoverIv.setImageResource(R.mipmap.logo_icon);
                }
            }
            if (mDetailAlbumSubCountTv != null) {
                if (album.getSubscribeCount()<10000) {
                    mDetailAlbumSubCountTv.setText(album.getSubscribeCount()+"");
                }else if (album.getSubscribeCount()<100000000) {
                    mDetailAlbumSubCountTv.setText(album.getSubscribeCount()/10000+"万");
                }else {
                    mDetailAlbumSubCountTv.setText(album.getSubscribeCount()/100000000+"亿");
                }
            }
            if (mDetailAlbumIntroTv != null) {
                if (album.getAlbumIntro() != null&&album.getAlbumIntro().length()!=0) {
                    mDetailAlbumIntroTv.setText("        "+ album.getAlbumIntro());
                }else {
                    mDetailAlbumIntroTv.setText("        "+"无简介内容");

                }
            }
        }

        @Override
        public void onSetDetailAlbumListData(List<Track> detailAlbumTracks) {
            if (mIsLoadMore && mTwinklingRefreshLayout!=null) {
                getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mTwinklingRefreshLayout.finishLoadmore();
                    }
                },500);
                mIsLoadMore = false;
            }

            this.mCurrentDetailAlbumTracks = detailAlbumTracks;
            mAdapterDetailAlbumRv.setData(detailAlbumTracks);
            mUiLoader.upDateStatus(ViewUILoader.UIStatus.SUCCESS);
        }

        @Override
        public void onError() {
            mUiLoader.upDateStatus(ViewUILoader.UIStatus.NETWORK_ERROR);
        }

        @Override
        public void onEmpty() {
            mUiLoader.upDateStatus(ViewUILoader.UIStatus.EMPTY);
        }

        @Override
        public void onLoading() {
            mUiLoader.upDateStatus(ViewUILoader.UIStatus.LOADING);
        }

        @Override
        public void onLodeMoreFinish(final int tracksSize) {
            getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (tracksSize>0) {
                        //Toast.makeText(DetailActivity.this,"成功加载"+tracksSize+"条节目",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(DetailActivity.this,"没有更多节目",Toast.LENGTH_SHORT).show();
                    }
                }
            },500);

        }

        @Override
        public void onRefreshFinish(int tracksSize) {

        }
    }






    private class OnRetryClickListener implements ViewUILoader.OnRetryClickListener {
        @Override
        public void onRetryClick() {
            //网络错误，点击重试，重新获取数据
            if (mInstanceImplDetailLogic != null) {
                mInstanceImplDetailLogic.getDetailAlbumListData((int) mCurrentId,mCurrentPage);
            }
        }
    }

    private class OnDetailAlbumItemClickListener implements AdapterTrackRv.OnDetailAlbumItemClickListener{
        @Override
        public void onDetailAlbumItemClick(List<Track> detailAlbumListData, int position) {
            //设置播放器所需数据
            ImplPlayerLogic instanceImplPlayerLogic = ImplPlayerLogic.getInstanceImplPlayerLogic();
            instanceImplPlayerLogic.setPlayListData(detailAlbumListData,position);

            Intent intent = new Intent(getContext(),PlayerActivity.class);
            startActivity(intent);
        }
    }

    private class PlayerViewCallBack implements IPlayerViewCallback{
        @Override
        public void onPlayStart() {
            //修改图标为暂停的状态，文字修改为正在播放
            updatePlaySate(true);
        }

        @Override
        public void onPlayPause() {
            updatePlaySate(false);
        }

        @Override
        public void onPlayStop() {
            updatePlaySate(false);
        }

        @Override
        public void onPlayError() {

        }

        @Override
        public void onPrePlay(Track track) {

        }

        @Override
        public void nextPlay(Track track) {

        }

        @Override
        public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {

        }

        @Override
        public void onListLoaded(List<Track> list) {

        }

        @Override
        public void onProgressChange(int currPos, int duration) {

        }

        @Override
        public void onAdLoading() {

        }

        @Override
        public void onAdFinished() {

        }

        @Override
        public void onTrackUpdate(Track track, int playIndex) {
            if (track != null) {
                mCurrentTrackTitle = track.getTrackTitle();
                if (!TextUtils.isEmpty(mCurrentTrackTitle) && mDetailPlayControlTv!=null) {
                    mDetailPlayControlTv.setText(mCurrentTrackTitle);
                }
            }
        }

        @Override
        public void updateListOrder(boolean isReverse) {

        }
    }



    private class SubscriptionPresenterCallback implements ISubscriptionPresenterCallback {
        @Override
        public void onAddResult(boolean isSuccess) {
            if (isSuccess) {
                if (mSubBtn != null) {
                    mSubBtn.setText(R.string.cancel_sub_text);
                }
            }
            String string = isSuccess ? "订阅成功" : "订阅失败";
            Toast.makeText(getAppContext(),string,Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onDeleteResult(boolean isSuccess) {
            if (isSuccess) {
                if (mSubBtn != null) {
                    mSubBtn.setText(R.string.sub_text);
                }
            }
            String string = isSuccess ? "删除成功" : "删除失败";
            Toast.makeText(getAppContext(),string,Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onSubscriptionsLoaded(List<Album> albums) {
            UtilLog.d(TAG,"订阅专辑尺寸 ==> "+albums.size());
            for (Album album : albums) {
                UtilLog.d(TAG,"订阅专辑标题 ==> "+album.getAlbumTitle());
            }
        }

        @Override
        public void onSubFull() {
            Toast.makeText(getAppContext(),"订阅数量不得超过"+ UtilConstants.MAX_SUB_COUNT,Toast.LENGTH_SHORT).show();
        }
    }
}
